import React, { useState, useEffect, useMemo } from 'react'
import { withRouter, RouteComponentProps, Link } from 'react-router-dom'
import { connect } from 'react-redux'
import './style.scss'
import { Avatar } from 'antd'
import moment from 'moment'
import { Layout, Badge, Popover, Empty } from 'antd'
import { StoreState } from '../../store'
import { logout } from '../../store/actions/user'
import { serviceGetInnerMessage } from '../../request/innermessage'
import { HomeMainState } from '../../views/home/main'
import { fullscreen, exitFullscreen } from '../../utils/helper'
import {
  PoweroffOutlined,
  MenuUnfoldOutlined,
  MenuFoldOutlined,
  BellFilled,
  BugFilled,
  GithubOutlined,
  FullscreenExitOutlined,
  FullscreenOutlined,
} from '@ant-design/icons'

const { Header } = Layout
const popoverList = [
  { name: '个人中心', path: '/home/setting/base' },
  { name: '消息通知', path: '/home/setting/notification' },
  { name: '账号设置', path: '/home/setting/account' },
]

type Props = ReturnType<typeof mapStateToProps> &
  HomeMainState &
  RouteComponentProps

const mapStateToProps = ({ user }: StoreState) => {
  return { userInfo: user.userInfo }
}

const PopoverContent = (
  <div className="popover-content">
    {popoverList.map(item => (
      <Link className="drop-item" to={item.path} key={item.name}>
        {item.name}
      </Link>
    ))}
    <div className="drop-item sign-out" onClick={() => logout()}>
      <PoweroffOutlined style={{ fontSize: '14px', marginRight: '5px' }} />
      <span>退出</span>
    </div>
  </div>
)

const HomeHeader: React.FC<Props> = function ({
  collapsed,
  setCollapsed,
  userInfo,
}: Props) {
  const [messageList, setMessageList] = useState([])
  const [unReadCount, setUnReadCount] = useState(0)
  const [isFullscreen, setIsFullscreen] = useState(false)

  useEffect(() => {
    serviceGetInnerMessage({ pageSize: 5 }).then(res => {
      if (res.data.success) {
        let count = 0
        const data = res.data.data.rows.map((item: any) => {
          item.createdAt = moment(item.createdAt).format('YYYY-MM-DD HH:mm')
          if (!item.hasRead) {
            count++
          }
          return item
        })
        // 未读消息
        setUnReadCount(count)
        // 消息列表
        setMessageList(data)
      }
    })
  }, [])

  // useMemo 返回一个memoized值
  // 把“创建”函数和依赖项数组作为参数传入 `useMemo`，它仅会在某个依赖项改变时才重新计算 memoized 值。这种优化有助于避免在每次渲染时都进行高开销的计算。
  // 记住，传入 `useMemo` 的函数会在渲染期间执行。请不要在这个函数内部执行与渲染无关的操作，诸如副作用这类的操作属于 `useEffect` 的适用范畴，而不是 `useMemo`。
  // 如果没有提供依赖项数组，`useMemo` 在每次渲染时都会计算新的值。
  const MessageContent = useMemo(
    () => (
      <div className="message-popover">
        <div className="msg-header item-block">
          <span className="left">站内消息通知</span>
          <Link className="right" to="/home/setting/notification">
            消息接收管理
          </Link>
        </div>
        {messageList.length > 0 ? (
          <>
            {messageList.map((item: any) => (
              <div className="item-block ls" key={item.id}>
                <div className="ellipsis">{item.content}</div>
                <div className="date">{item.createdAt}</div>
              </div>
            ))}
            <Link
              className="item-block ls"
              to="'/home/setting/innerMessage'"
            ></Link>
          </>
        ) : (
          <Empty style={{ padding: '20px 0' }}></Empty>
        )}
      </div>
    ),
    [messageList],
  )
  // BUG：按ESC退出全屏，再点击全屏会报错
  function handleFullscreen() {
    // 函数式更新：如果你的更新函数返回值与当前 state 完全相同，则随后的重渲染会被完全跳过。
    setIsFullscreen(isFullscreen => {
      isFullscreen ? exitFullscreen() : fullscreen()
      return !isFullscreen
    })
  }
  return (
    <Header>
      <div className="left">
        {collapsed ? (
          <MenuUnfoldOutlined
            onClick={setCollapsed}
            style={{ cursor: 'pointer', fontSize: '20px' }}
          />
        ) : (
          <MenuFoldOutlined
            onClick={setCollapsed}
            style={{ cursor: 'pointer', fontSize: '20px' }}
          ></MenuFoldOutlined>
        )}
      </div>
      <ul className="right">
        <Popover content={MessageContent}>
          <li>
            <Badge count={unReadCount} overflowCount={9} size="small">
              {/* 铃声按钮 */}
              <BellFilled />
            </Badge>
          </li>
        </Popover>
        <li onClick={handleFullscreen}>
          {isFullscreen ? (
            <Popover content="退出全屏" placement="bottom">
              <FullscreenExitOutlined />
            </Popover>
          ) : (
            <Popover content="全屏" placement="bottom">
              <FullscreenOutlined />
            </Popover>
          )}
        </li>
        <li>
          <a
            href="https://gitee.com/Jay_Ohhh/carefree-admin/issues"
            target="_blank"
            rel="noopener noreferrer"
          >
            {/* Bug按钮 */}
            <BugFilled></BugFilled>
          </a>
        </li>
        <li>
          <a
            href="https://gitee.com/Jay_Ohhh/carefree-admin"
            target="_blank"
            rel="noopenner noreferrer"
          >
            <GithubOutlined></GithubOutlined>
          </a>
        </li>
        <Popover placement="bottomRight" content={PopoverContent}>
          <li>
            <Avatar src={userInfo.avatarUrl} />
            <span className="username">{userInfo.username}</span>
          </li>
        </Popover>
      </ul>
    </Header>
  )
}

export default connect(mapStateToProps)(withRouter(HomeHeader))
